package com.rgst.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rgst.dao.entity.SecPermission;
import com.rgst.dao.repository.SecPermissionRepository;
import com.rgst.dto.Result;

/**
 * Created by tancw on 2017/3/21.
 */
@Controller
public class HomeController implements ErrorController {

    @Autowired
    private SecPermissionRepository secPermissionRepository;

    @RequestMapping("/")
    public String index(Model model) {
        return "redirect:index";
    }

    @RequestMapping("/index")
    public ModelAndView home() {
        ModelAndView modelAndView = new ModelAndView();
        Sort sort = new Sort(Sort.Direction.ASC, "orderno");
        List<SecPermission> permissions = secPermissionRepository.findAll(sort);
        modelAndView.addObject("menus", permissions);
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @RequestMapping("/tologin")
    public String tologin(Model model) {
        return "signin";
    }

    @RequestMapping("logout")
    public String logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "signin";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(@NotNull String username, @NotNull String password) {
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            return Result.success("登录成功");
        } catch (Exception e) {
            return Result.error("登录失败");
        }
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    @ResponseBody
    public Result handlerError() {
        return Result.error("处理失败");
    }
}
